<template>
  <div class="login-wrapper">
    <div style="width: 30%"></div>
    <div class="login-box view-box">
      <div class="box-title">科兴创达~</div>
      <div class="main-ways">
        <el-form ref="apForm" key="apForm" v-if="loginWay === 1" :model="apForm" :rules="apRules">
          <el-form-item label="账号" prop="account">
            <el-input v-model="apForm.account" placeholder="请输入账号或用户名"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="apForm.password" placeholder="请输入密码" show-password></el-input>
          </el-form-item>
          <div class="primary-btn" @click="onPasswordLogin()">登录</div>
          <div class="bottom">
            <div @click="changeLoginWay(2)" class="change-way">手机号登录</div>
            <div>忘记密码</div>
          </div>
        </el-form>

        <el-form ref="psForm" key="psForm" v-else-if="loginWay === 2" :model="psForm" :rules="psRules">
          <el-form-item label="手机号" prop="phoneNo">
            <el-input placeholder="手机号" v-model="psForm.phoneNo" class="input-with-select">
              <template slot="prepend">
                <el-select style="width: 80px" v-model="psForm.phoneArea" placeholder="地区">
                  <el-option label="+86" value="86"></el-option>
                </el-select>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="验证码" prop="smsCode">
            <el-input v-model="psForm.smsCode" placeholder="验证码">
              <template slot="append">
                <div :class="smsCountDown <= 0 ? 'get-sms':'wait-sms'" @click="onSMSSend">
                  <span>{{ getSendBtnText }}</span>
                </div>
              </template>
            </el-input>
          </el-form-item>
          <div class="primary-btn" @click="onSMSLogin">登录 / 注册</div>
          <div class="bottom">
            <div @click="changeLoginWay(1)" class="change-way">账号密码登录</div>
            <div></div>
          </div>
        </el-form>


        <div class="notice">注册或登录即代表同意长科的《用户协议》和《隐私协议》</div>
      </div>
      <div class="other-ways">
        <div>-- 其他登陆方式 --</div>
        <div class="flex-box thirds">
          <div>

          </div>
          <div>

          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {mapActions} from "vuex";

export default {
  name: 'login',
  data() {
    const passwordV = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('密码不能为空'));
      }
      setTimeout(() => {
        if ((value + '').length < 6) {
          callback(new Error('密码长度至少为6个字符'));
        } else {
          callback();
        }
      }, 1000);
    };
    const accountV = (rule, value, callback) => {
      console.log(value);
      if (value === '') {
        callback(new Error('请输入账号或用户名'));
      } else {
        callback();
      }
    };
    const phoneV = (rule, value, callback) => {
      console.log(value);
      if (!value) {
        callback(new Error('请输入手机号'));
      } else {
        let checkPhone = new RegExp(/^1([3-9])\d{9}$/);
        if (!checkPhone.test(value)) {
          callback(new Error('手机号不合法'));
        } else {
          callback();
        }
      }
    };
    const smsV = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入验证码'));
      } else {
        if (value.length !== 6) {
          callback(new Error('验证码长度仅为6'));
        } else {
          callback();
        }
      }
    };
    return {
      apForm: {
        account: '',
        password: ''
      },
      apRules: {
        account: [
          {validator: accountV, trigger: 'blur'}
        ],
        password: [
          {validator: passwordV, trigger: 'blur'}
        ]
      },
      psForm: {
        phoneNo: '',
        phoneArea: '',
        smsCode: ''
      },
      psRules: {
        phoneNo: [
          {validator: phoneV, trigger: 'blur'}
        ],
        smsCode: [
          {validator: smsV, trigger: 'blur'}
        ]
      },
      loading: false,
      showPassword: false, //是否显示明文
      loginWay: 2, //1: 账密，2：验证码
      smsCountDown: 0,
      smsCountInterval: null,
      toggleDelay: false,
      version: "",
      //第三方登录相关信息
      thirdType: "",
      thirdLoginInfo: "",
      thirdLoginState: false,
      bindingPhoneModal: false,
      thirdUserUuid: "",
      url: {
        bindingThirdPhone: "/sys/thirdLogin/bindingThirdPhone",
      },
    };
  },
  computed: {
    isSendSMSEnable() {
      return this.smsCountDown <= 0 && this.phoneNo.length > 4;
    },
    getSendBtnText() {
      if (this.smsCountDown > 0) {
        return this.smsCountDown + "秒后重发";
      } else {
        return "获取验证码";
      }
    },
    canSMSLogin() {
      return this.userName.length > 4 && this.smsCode.length > 4;
    },
    canPwdLogin() {
      return this.userName.length > 4 && this.password.length > 4;
    },
  },
  methods: {
    ...mapActions(["mLogin", "passwordLogin", "PhoneLogin", "ThirdLogin"]),


    changeLoginWay(loginWay) {
      this.loginWay = loginWay;
    },

    onPasswordLogin() {
      let loginParams = {
        phone: this.apForm.account,
        password: this.apForm.password,
      };
      console.log("执行1")
      this.passwordLogin(loginParams)
          .then(() => {
            this.$router.push({
              name: "home",
            });
          })
    },


    onSMSSend() {
      if (this.smsCountDown > 0) return;
      let smsParams = {};
      smsParams.phone = this.psForm.phoneNo;
      smsParams.email = ""

      let checkPhone = new RegExp(/^1([3-9])\d{9}$/);
      if (!smsParams.phone || smsParams.phone.length === 0) {
        this.$message.error('手机号不能为空');
        return false;
      }
      if (!checkPhone.test(smsParams.phone)) {
        this.$message.error('手机号不合法');
        return false;
      }
      console.log(smsParams)
      this.$api.sendVerificationCode(smsParams)
      this.smsCountDown = 60;
      this.startSMSTimer();
    },
    startSMSTimer() {
      this.smsCountInterval = setInterval(() => {
        this.smsCountDown--;
        if (this.smsCountDown <= 0) {
          clearInterval(this.smsCountInterval);
        }
      }, 1000);
    },
    onSMSLogin() {
      let loginParams = {
        phone: this.psForm.phoneNo,
        code: this.psForm.smsCode,
      };
      this.mLogin(loginParams)
          .then((res) => {
            let userInfo = res.data.data
            if (userInfo.status === -2) {
              // 完全新用户需要完善信息并判断是否需要绑定协会
              this.$router.push({
                name: "register",
                query:{
                  status:-2
                }
              });
            } else if (userInfo.status === -1) {
              // 企业激活新用户需要完善信息
              this.$router.push({
                name: "register",
                query:{
                  status:-1
                }
              });
            } else {
              this.$router.push({
                name: "home",
              });
            }
          })
    },


    psLogin() {

      if (!this.smsCode || this.smsCode.length === 0) {
        return;
      }
      let loginParams = {
        mobile: this.phoneNo,
        captcha: this.smsCode,
      };
      this.PhoneLogin(loginParams)
          .then((res) => {
            console.log("res====》", res);
            if (res.data.success) {
              this.$tip.success("登录成功!");
              this.$router.push({
                name: "home",
              });
            } else {
              this.$tip.error(res.data.message);
            }
          })
          .catch((err) => {
            let msg =
                ((err.response || {}).data || {}).message ||
                err.data.message ||
                "请求出现错误，请稍后再试";
            this.$tip.error(msg);
          });
    },
    loginSuccess() {
      // 登陆成功，重定向到主页
      let to;
      if (this.$route.query.fromPath) {
        to = this.$route.query.fromPath.toString();
      } else {
        to = {
          name: 'home'
        }
      }
      this.$router.push(to);
    },
    requestFailed() {
      this.$message.warning("登录失败");
    },
  },
  mounted() {
    // alert('mounted');
  },
  beforeDestroy() {
    if (this.smsCountInterval) {
      clearInterval(this.smsCountInterval);
    }
  },
};
</script>

<style lang="scss" scoped>
.login-wrapper {
  background-image: url("./../../assets/login/login-bg.png");
  background-size: cover;
  overflow: hidden;
  min-height: 100vh;
  display: flex;
  flex-direction: row;
  justify-content: space-around;
  align-items: center;
  //background-image: linear-gradient(to right top, #eaeaee, #eeeef1, #f2f2f4, #f6f6f8, #fafafb, #f5f5fc, #acc4ff, #8eb9ff);
}

.el-form-item {
  margin-bottom: 15px;
}

.login-box {
  width: 360px;
  height: 580px;
  padding: 20px 100px;
  margin: 20px auto 0;
  background: #fff;
  border-radius: 10px;

}

.box-title {
  font-size: 28px;
  font-weight: bolder;
  margin: 20px 0;
}

.main-ways {
  display: flex;
  flex-direction: column;

  .get-sms {
    cursor: pointer;
  }

  .wait-sms {
    cursor: wait;
  }

  .bottom {
    display: flex;
    justify-content: space-between;
    font-size: 14px;
    margin: 20px 0;

    > div {
      cursor: pointer;
      transition: .3s;

      &:hover {
        color: #8EB9FF;
        transition: .3s;
      }
    }
  }

  .primary-btn {
    margin-top: 30px;
    width: inherit;
  }

  .notice {
    font-size: 12px;
    color: #7a7a7a;
  }
}

.other-ways {
  margin-top: 50px;
  text-align: center;
  font-size: 14px;

  .thirds {
    margin-top: 10px;
    justify-content: center;

    > div {
      width: 50px;
      height: 50px;
      border-radius: 50%;
      background: #eaeaea;
      margin: 10px;
    }
  }
}
</style>

